package com.itheima.service.mongo.impl;

import com.itheima.domain.mongo.Friend;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.service.mongo.FriendService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class FriendServiceImpl implements FriendService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public void addContacts(Long loginUserId, Long friendId) {
        //添加双方好友
        //1.添加我和对方的关系
        //1.1 查询我和对方是否有好友
        Query query = new Query(
                Criteria.where("userId").is(loginUserId).and("friendId").is(friendId)
        );
        Friend friend = mongoTemplate.findOne(query, Friend.class);
        //1.2 如果没有添加关系
        if(friend == null){
            friend = new Friend();
            friend.setUserId(loginUserId);
            friend.setFriendId(friendId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }

        //2.添加对方和我的关系
        //2.1 查询对象和我是否有好友
        Query query2 = new Query(
                Criteria.where("userId").is(friendId).and("friendId").is(loginUserId)
        );
        Friend friend2 = mongoTemplate.findOne(query2, Friend.class);
        //2.2 如果没有添加关系
        if(friend2 == null){
            friend2 = new Friend();
            friend2.setUserId(friendId);
            friend2.setFriendId(  loginUserId);
            friend2.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend2);
        }
    }

    /**
     * 查询当前用户的好友列表
     * @param page
     * @param pageSize
     * @param loginUserId
     * @return
     */
    @Override
    public PageBeanVo findContactList(Integer page, Integer pageSize, Long loginUserId) {
        int startIndex = (page-1)*pageSize;
        Query query = new Query(
                Criteria.where("userId").is(loginUserId)
        ).skip(startIndex).limit(pageSize);
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        long count = mongoTemplate.count(query, Friend.class);
        return new PageBeanVo( page, pageSize , count , friendList);
    }

    //删除friend表中的数据
    @Override
    public void deleteContacts(Long userId, Long loginUserId) {
        Query query = new Query(
                Criteria.where("userId").is(loginUserId).and("friendId").is(userId)
        );

        mongoTemplate.remove(query, Friend.class);
        Query query1 = new Query(
                Criteria.where("userId").is(userId).and("friendId").is(loginUserId)
        );

        mongoTemplate.remove(query1, Friend.class);
    }
}
